package com.ygqh.baby.controller.mobile;

import com.alibaba.fastjson.JSON;
import com.ygqh.baby.ao.*;
import com.ygqh.baby.constant.RedisConstant;
import com.ygqh.baby.model.*;
import com.ygqh.baby.po.*;
import com.ygqh.baby.redis.RedisDao;
import com.ygqh.baby.service.*;
import com.ygqh.baby.utils.DateConvertUtils;
import com.ygqh.baby.utils.SessionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.util.*;

/**
 * 我的返利
 *
 * @author guohao
 */
@Controller
@RequestMapping("/app/rebate")
public class YgMyRebateController extends BaseController {

	@Autowired
	private YgUserBalanceService ygUserBalanceService;
	@Autowired
	private YgCommissionService ygCommissionService;
	@Value("${promotion.link}")
	protected String promotionLink;
	@Autowired
	private YgCommissionService commissionService;
	@Autowired
	private YgUserService userService;
	@Autowired
	private YgUserCultivationDayService ygUserCultivationDayService;
	@Autowired
	private YgAgentInviteRecordService ygAgentInviteRecordService;
	@Autowired
	private YgUserBalanceDetailService ygUserBalanceDetailService;
	@Autowired
	private YgUserService ygUserService;
	@Autowired
	private RedisDao redisDao;

	@RequestMapping(value = "getMyAccount")
	@ResponseBody
	public ResponseEntity getMyAccount() {
		YgUser user = SessionUtil.getCurrentUser();
		YgUserBalance balance = ygUserBalanceService.findByUserId(user.getId());
		Map<String, BigDecimal> map = new HashMap<>();
		map.put("balancePrice", balance.getBalancePrice());
		return ResponseEntity.success(map);
	}

	@RequestMapping("findMyRebate")
	@ResponseBody
	public ResponseEntity getMyRebate() {
		YgUser user = SessionUtil.getCurrentUser();
		Map<String, Object> map = new HashMap<>();
		YgUserBalance balance = ygUserBalanceService.findByUserId(user.getId());
		int count;
		if (UserType.Group.equals(user.getUserType())) {
			count = userService.findUserRecommendCount(null, user.getGroupTag());
		} else {
			count = userService.findUserRecommendCount(user.getSourceCode(), null);
		}
		// 预收入
		map.put("preincomePrice", balance.getPreincomePrice());
		// 可提现
		map.put("balancePrice", balance.getBalancePrice());
		// 已提现
		map.put("withdrawPrice", balance.getWithdrawPrice());
		// 推荐用户数
		map.put("userRecommendCount", count);
		Map<String, Object> shareOrderPrice = ygUserBalanceService.getUserShareOrderPrice(user.getId());
		map.putAll(shareOrderPrice);
		return ResponseEntity.success(map);
	}

	/**
	 * 预收入详细列表
	 *
	 * @param queryInfo
	 * @return
	 */
	@RequestMapping("findBalanceDetails")
	@ResponseBody
	public ResponseEntity findBalanceDetails(QueryInfo queryInfo) {
		YgUser user = SessionUtil.getCurrentUser();
		List<YgUserBalanceDetailModel> list = ygUserBalanceService.
				findBalanceDetailsByType(queryInfo, user.getId(), null, "PreIncome", null);
		return ResponseEntity.success(list);
	}

	@RequestMapping("findShareOrderInfo")
	@ResponseBody
	public ResponseEntity findShareOrderInfo(Long orderId) {
		YgUserShareOrderModel model = ygUserBalanceService.findShareOrderInfo(orderId);
		return ResponseEntity.success(model);
	}

	@RequestMapping("findOrderList")
	@ResponseBody
	public ResponseEntity findOrderList(QueryInfo queryInfo) {
		YgUser user = SessionUtil.getCurrentUser();
		List<YgUserShareOrderModel> model = ygUserBalanceService.getUserShareOrder(queryInfo, user);
		// List<YgUserBalanceOrderModel> model =
		// ygUserBalanceService.findOrderList(queryInfo, user.getSourceCode());
		return ResponseEntity.success(model);
	}

	@RequestMapping("findOrderBalanceDetail")
	@ResponseBody
	public ResponseEntity findOrderBalanceDetail(String ubdOrderId, OperationType operationType, BalanceType balanceType, Long userId) {
		Long uid;
		if (userId != null) {
			uid = userId;
		} else {
			YgUser user = SessionUtil.getCurrentUser();
			uid = user.getId();
		}
		YgUserBalanceOrderInfo model = ygUserBalanceService.findOrderBalanceDetailV2(ubdOrderId, balanceType, operationType, uid);
		return ResponseEntity.success(model);
	}

	@RequestMapping("bindBank")
	@ResponseBody
	public ResponseEntity bindBank(Long bankId, String bankAccount, String alipayCode) {
		YgUser user = SessionUtil.getCurrentUser();
		int row = ygCommissionService.bindBank(user.getId(), bankId, bankAccount, "", "", "", alipayCode);
		return ResponseEntity.success(row);
	}

	@RequestMapping("findBankInfo")
	@ResponseBody
	public ResponseEntity findBankInfo() {
		YgUser user = SessionUtil.getCurrentUser();
		YgUserBank bank = ygCommissionService.findBankInfo(user.getId());
		return ResponseEntity.success(bank);
	}

	/**
	 * 申请提现
	 *
	 * @param commissionPrice
	 * @return
	 */
	@RequestMapping("applyWithdrawals")
	@ResponseBody
	public ResponseEntity applyWithdrawals(BigDecimal commissionPrice) {
		YgUser user = SessionUtil.getCurrentUser();
		int row = ygCommissionService.applyWithdrawals(user.getId(), user.getUserName(), commissionPrice, PLATFORM_NO);
		return ResponseEntity.success(row);
	}

	/**
	 * 查找可提现金额列表
	 *
	 * @param queryInfo
	 * @return
	 */
	@RequestMapping("findWithdrawableMoney")
	@ResponseBody
	public ResponseEntity findWithdrawableMoney(QueryInfo queryInfo) {
		YgUser user = SessionUtil.getCurrentUser();
		List<YgUserBalanceDetailModel> list = ygUserBalanceService.findBalanceDetailsByType(queryInfo, user.getId(),
				"balance", null, null);
		return ResponseEntity.success(list);
	}

	/**
	 * 查找提现记录
	 *
	 * @param queryInfo
	 * @return
	 */
	@RequestMapping("findWithdrawMoneyRecord")
	@ResponseBody
	public ResponseEntity findWithdrawMoneyRecord(QueryInfo queryInfo) {
		YgUser user = SessionUtil.getCurrentUser();
		ResultSet<YgCommissionModel> resultSet = commissionService.searchModel(queryInfo, user.getId(),
				null, null);
		return ResponseEntity.success(resultSet.toDatatables(null));
	}

	/**
	 * 查找已提现金额
	 *
	 * @param queryInfo
	 * @return
	 */
	@RequestMapping("findWithdrewMoney")
	@ResponseBody
	public ResponseEntity findWithdrewMoney(QueryInfo queryInfo) {
		YgUser user = SessionUtil.getCurrentUser();
		ResultSet<YgCommissionModel> resultSet = commissionService.searchModel(queryInfo, user.getId(),
				new String[]{CommissionStatus.PaySuccess.name(), CommissionStatus.WaitingPay.name()}, null);
		return ResponseEntity.success(resultSet.getResult());
	}

	/**
	 * 提现
	 *
	 * @return
	 */
	@RequestMapping("withdraw")
	@ResponseBody
	public ResponseEntity withdraw(BigDecimal money) {

		YgUser user = SessionUtil.getCurrentUser();
		Message message;
		try {
			message = commissionService.withdraw(user, money, PLATFORM_NO);
		} catch (Exception e) {
			message = Message.error("提现失败", null);
			e.printStackTrace();
		}
		return ResponseEntity.converter(message);
	}

	/**
	 * 提现进度
	 *
	 * @return
	 */
	@RequestMapping("findRateOfProgress")
	@ResponseBody
	public ResponseEntity findRateOfProgress(Long commissionId) {
		return ResponseEntity.success(commissionService.findModelById(commissionId));
	}

	/**
	 * 代理用户耕耘成果
	 *
	 * @return
	 */
	@RequestMapping(value = "getUserCultivation")
	@ResponseBody
	public ResponseEntity findUserCultivation() {
		YgUser user = SessionUtil.getCurrentUser();
		List<YgUserCultivationDayModel> userCultivation = ygUserCultivationDayService.queryUserCultivationGroupByUserId(user.getId());
		List<YgUserCultivationDayModel> userCultList = new ArrayList<YgUserCultivationDayModel>();

		String today = DateConvertUtils.format(new Date());
		YgAgentInviteRecord agentInviteRecord = ygAgentInviteRecordService.findRecordForYijiandian(user.getId());
		if (agentInviteRecord == null || agentInviteRecord.getCancelTime() != null) {
			return ResponseEntity.success(userCultList);
		}
		String startDate = DateConvertUtils.format(DateConvertUtils.addMonth(agentInviteRecord.getReceiveTime(), -1), "yyyy-MM-dd");
		List<String> months = DateConvertUtils.diffMonth(startDate, today);

		for (String mon : months) {
			boolean blag = true;
			for (YgUserCultivationDayModel userCult : userCultivation) {
				if (mon.equals(userCult.getMonth())) {
					blag = false;
					userCultList.add(userCult);
					break;
				}
			}
			if (blag) {
				YgUserCultivationDayModel userCult = new YgUserCultivationDayModel();
				userCult.setMonth(mon);
				userCult.setTotalPrice(new BigDecimal(0.00));
				userCultList.add(userCult);
			}
		}
		userCultList.sort((o1, o2) -> {
			Date date1 = DateConvertUtils.parse(o1.getMonth(), "yyyy-MM");
			Date date2 = DateConvertUtils.parse(o2.getMonth(), "yyyy-MM");
			return date2.compareTo(date1);
		});
		return ResponseEntity.success(userCultList);
	}

	/**
	 * 按月查询耕耘成果明细
	 *
	 * @param month 年月 例：2018-05
	 * @return
	 */
	@RequestMapping("findOrderListByMonth")
	@ResponseBody
	public ResponseEntity findOrderListByMonth(Date month) {
		YgUser user = SessionUtil.getCurrentUser();
		if (month == null) { // 默认当月
			month = new Date();
		}
		Date monthStartDate = DateConvertUtils.getMonthStartDate(month);
		Date monthEndDate = DateConvertUtils.getMonthEndDate(month);
		List<YgUserCultivationDay> list = ygUserCultivationDayService.findByUserIdAndDay(monthStartDate, monthEndDate, user.getId());
		BigDecimal totalPriceByMonth = list.stream().map(YgUserCultivationDay::getTotalPrice).reduce(ZERO, BigDecimal::add);
		Map<String, Object> data = new HashMap<>();
		data.put("totalPriceByMonth", totalPriceByMonth);
		data.put("userCultivationList", list);
		return ResponseEntity.success(data);
	}

	/**
	 * 会员页面相关数据
	 *
	 * @return 响应数据
	 * @date 2019-03-29 16:50
	 * @version 2.0
	 */
	@RequestMapping(value = "findMyRebate", params = {"version=2.0"})
	@ResponseBody
	public ResponseEntity getMyRebateV2() {
		YgUser user = SessionUtil.getCurrentUser();
		Map<String, Object> result = new HashMap<>();
		// 可提现及预收入数据
		result.putAll(ygUserBalanceDetailService.findMyRebate(user.getId(), null));
		// 粉丝数据
		result.putAll(ygAgentInviteRecordService.findRecommendUserCount(user.getId(), null));
		// 我的邀请人
		YgAgentInviteRecord record = ygAgentInviteRecordService.findRecordForYijiandian(user.getId());
		if (record != null) {
			YgUser fromUser = ygUserService.findById(record.getUserId());
			result.put("fromNickName", fromUser.getNickName());
			result.put("fromHeadImageUrl", fromUser.getHeadImageUrl());
		}
		return ResponseEntity.success(result);
	}

	/**
	 * 获取成为代理的条件
	 *
	 * @return
	 */
	@RequestMapping("conditionForRechargeUserAgent")
	@ResponseBody
	public ResponseEntity conditionForRechargeUserAgent() {
		String result = redisDao.get(String.format(RedisConstant.USER_AGENT_CONDITION_PREFIX_KEY, SALES_PLATFORM));
		return ResponseEntity.success(JSON.parseObject(result, Map.class));
	}

	/**
	 * 收益明细
	 *
	 * @param queryInfo 分页
	 * @param tabType   页面展示类型（ALL,MONTH,TODAY）
	 * @return
	 */
	@RequestMapping("incomeList")
	@ResponseBody
	public ResponseEntity incomeList(QueryInfo queryInfo, @RequestParam(defaultValue = "ALL") String tabType) {
		Date limitDate;
		switch (tabType) {
			case "MONTH":
				limitDate = DateConvertUtils.getMonthStartDate(new Date());
				break;
			case "TODAY":
				limitDate = DateConvertUtils.getDateStart(new Date());
				break;
			case "ALL":
			default:
				limitDate = null;
				break;
		}
		List<UserBalanceDetailModel> detailList = ygUserBalanceDetailService.
				findDetailList(queryInfo, SessionUtil.getCurrentUser().getId(), limitDate, null, BalanceType.PreIncome);
		return ResponseEntity.success(detailList);
	}

	/**
	 * 收益汇总
	 *
	 * @return
	 */
	@RequestMapping("rebateCollect")
	@ResponseBody
	public ResponseEntity rebateCollect() {
		Map<String, Object> myRebate =
				ygUserBalanceDetailService.findMyRebate(SessionUtil.getCurrentUser().getId(), null);
		return ResponseEntity.success(myRebate);
	}
}
